package com.itic.mall.system.pay.userlog.service;

import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.plugins.mybatis.Page;
import com.itic.appbase.framework.type.*;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.msg.vo.MsgVO;
import com.itic.mall.mobile.users.info.OrderItemVo;
import com.itic.mall.mobile.users.info.PayUserlogVo;
import com.itic.mall.mobile.users.info.PreIncomeVo;
import com.itic.mall.mobile.users.info.UserPreincomeVo;
import com.itic.mall.system.inter.orders.item.persistence.model.OrdersItem;
import com.itic.mall.system.inter.pay.userlog.persistence.dao.PayUserlogDao;
import com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlog;
import com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample;
import com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample.Criteria;
import com.itic.mall.system.inter.project.commission.persistence.model.ProjectCommission;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.msg.apppush.service.AppPushService;
import com.itic.mall.system.orders.item.service.OrdersItemService;
import com.itic.mall.system.project.commission.service.ProjectCommissionService;
import com.itic.mall.system.users.usersmall.service.UsersMallService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class PayUserlogService
     extends CrudService<PayUserlogDao,PayUserlog,PayUserlogExample> {
    @Autowired
    private PayUserlogDao payUserlogDao;
    @Autowired
    private UsersMallService usersMallService;
    @Autowired
    private ProjectCommissionService projectCommissionService;
    @Autowired
 	protected OutCommonService outCommonService;
    @Autowired
    private AppPushService appPushService;
    @Autowired
    private OrdersItemService ordersItemService;
    
   	private static final String TYPE = "T_DM_T_USERS_MALL_TYPE";// 代码表名称
   	private static final String LAIYUAN = "T_DM_T_USERS_MALL_LAIYUAN";
   	private static final String PRE_INCOME_CHANNEL = "T_DM_T_PAY_USER_LOG_PRE_INCOME_CHANNEL";
   	private static final String PRE_OPERATE_TYPE = "T_DM_T_PAY_USER_LOG_PRE_OPERATE_TYPE";
   	private static final String PRE_INCOME_TYPE = "T_DM_T_PAY_USER_LOG_PRE_INCOME_TYPE";	
   	private static final String PAY_TYPE = "T_DM_T_PAY_USER_LOG_PAY_TYPE";
   	private static final String USER_TYPE = "T_DM_T_USERS_MALL_TYPE";
   	private static final String EXPEND_TYPE = "T_DM_T_PAY_USER_LOG_EXPEND_TYPE";
   	private static final String WITHDRAW_STATE = "T_DM_T_PAY_USER_LOG_WITHDRAW_STATE";
   	private static final String JIESUAN = "T_DM_T_PAY_USER_LOG_IS_JIESUAN";
    /**
	 * 获取用户支付信息返回数据
	 * @param payList
	 * @param userId
	 * @return
	 */
	public List<UserPreincomeVo> getPreincomeVo(List<PayUserlog> payList, String userId) {
		List<UserPreincomeVo> preList = new ArrayList<UserPreincomeVo>();
		String buyerUserId = null;
		String userNickName = null;
		String userPhone = null;
		String type = null;
		for (PayUserlog payUserlog : payList) {
			String orderNo = payUserlog.getOrderNo();
			String skuId = payUserlog.getSkuId();
			String channel = payUserlog.getPreIncomeChannel();
			String pretype = payUserlog.getPreType();
			OrderItemVo OrderItemVo = ordersItemService.getOrderItemVo(channel,pretype,orderNo,skuId);
			// 获取每个订单项的用户信息
			UsersMall usersMall = usersMallService.get(OrderItemVo.getUserId());
			if (usersMall != null) {
				buyerUserId = usersMall.getId();
				userNickName = usersMall.getUserNickName();
				userPhone = usersMall.getUserPhone();
				type = outCommonService.getNameByCode(TYPE, usersMall.getType());
			}
			payUserlog.setPreIncomeType(outCommonService.getNameByCode(PRE_INCOME_TYPE, payUserlog.getPreIncomeType()));
			payUserlog.setPreOperateType(
					outCommonService.getNameByCode(PRE_OPERATE_TYPE, payUserlog.getPreOperateType()));
			UserPreincomeVo userPreincomeVo = new UserPreincomeVo();

			String orderDesc = OrderItemVo.getOrderItemDesc();
			userPreincomeVo.setChannel(outCommonService.getNameByCode(PRE_INCOME_CHANNEL, payUserlog.getPreIncomeChannel()));
			userPreincomeVo.setCreateTime(payUserlog.getCreateTime());
			userPreincomeVo.setDescribe(orderDesc);
			userPreincomeVo.setType(type);
			userPreincomeVo.setUserNickName(userNickName);
			userPreincomeVo.setUserPhone(userPhone);
			userPreincomeVo.setUserId(buyerUserId);
			userPreincomeVo.setPreIncomeType(payUserlog.getPreIncomeType());
			userPreincomeVo.setPreOperateType(payUserlog.getPreOperateType());
			userPreincomeVo.setMoney(Double.toString(payUserlog.getPreAmount()));
			preList.add(userPreincomeVo);
		}
		return preList;
	}
    /**
	 * 根据查询条件获取用户支付日志表
	 * @param ordersItem
	 * @param userId
	 * @param preType
	 * @param type
	 * @param users
	 * @param PayUserlog
	 * @param request
	 * @return
	 */
	public PayUserlogExample getPayUserlog(String jiesuan,List<String> orderNos,OrdersItem ordersItem,String userId,String preType,String type,UsersMall users,PayUserlog PayUserlog,HttpServletRequest request){
		PayUserlogVo payUserlogVo = new PayUserlogVo();
		List<PayUserlog> paylist = null;
		List<String> payids = new ArrayList<String>();
		int total = 0;
		PayUserlogExample example = new PayUserlogExample();
		if(StringHelper.isNotBlank(userId)){
   			com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example.createCriteria();
   			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   			criteria.andUserIdEqualTo(userId);
   			if(users != null){
   				Date startTime = users.getCreateTime();
   				Date endTime = users.getUpdateTime();
   				if(startTime != null && endTime != null){
   					criteria.andCreateTimeBetween(startTime, endTime);
   				}
   			}
   			if(orderNos != null){
   				if(orderNos.size()>0){
   	   				criteria.andOrderNoIn(orderNos);
   	   			}
   			}
   			if(StringHelper.isNotBlank(jiesuan)){
   				if(jiesuan.equals(PreType.actual.getType())){
   					criteria.andPreTypeEqualTo(jiesuan);
   				}
   				if(jiesuan.equals(PreType.pre.getType())){
   					criteria.andPreTypeEqualTo(jiesuan);
   					criteria.andPreIncomeTypeNotEqualTo(PreIncomeType.tradeColse.getType());
   				}
   				if(jiesuan.equals(PreIncomeType.tradeColse.getType())){
   					criteria.andPreIncomeTypeEqualTo(jiesuan);
   				}
   			}
   			if(PayUserlog != null){
   				if(StringHelper.isNotBlank(PayUserlog.getPreType())){
   					//店铺订单获取规则：预估未转为累计的，只要展示预估的，预估已经转为累计的只展示累积的
   					if(!PayUserlog.getPreType().equals(PreType.pre.getType()) && !PayUserlog.getPreType().equals(PreType.actual.getType())){
   						payids = this.payUserlogDao.getPayUserlogIds(userId);
   					}else{
   	   					criteria.andPreTypeEqualTo(PayUserlog.getPreType());
   					}
   				}
   				if(payids.size()>0){
   					criteria.andIdIn(payids);
   				}
   				if(StringHelper.isNotBlank(PayUserlog.getPayType())){
   					criteria.andPayTypeEqualTo(PayUserlog.getPayType());
   				}
   				if(StringHelper.isNotBlank(PayUserlog.getPreIncomeType())){
   					criteria.andPreIncomeTypeEqualTo(PayUserlog.getPreIncomeType());
   				}
   				if(StringHelper.isNotBlank(PayUserlog.getPreIncomeChannel())){
   					criteria.andPreIncomeChannelEqualTo(PayUserlog.getPreIncomeChannel());
   				}
   				if(StringHelper.isNotBlank(PayUserlog.getOrderNo())){
   					criteria.andOrderNoEqualTo(PayUserlog.getOrderNo());
   				}
   				if(StringHelper.isNotBlank(PayUserlog.getWithdrawState())){
   					criteria.andWithdrawStateEqualTo(PayUserlog.getWithdrawState());
   				}
   				if(StringHelper.isNotBlank(PayUserlog.getNote())){
   					if(PayUserlog.getCreateTime() != null && PayUserlog.getUpdateTime() != null){
   						criteria.andCreateTimeBetween(PayUserlog.getCreateTime(), PayUserlog.getUpdateTime());
   					}
   				}
   			}
   			if(StringHelper.isNotBlank(preType)){
   	   			criteria.andPreTypeEqualTo(preType);
   			}
   			//提现类型
   			if(StringHelper.isNotBlank(type)){
   				criteria.andTypeEqualTo(type);
   			}
   			paylist = this.payUserlogDao.selectByExample(example);
   			//根据订单项查询条件查询
   			if(ordersItem != null){
   				if(StringHelper.isNotBlank(ordersItem.getGoodsName())){
   					List<String> ids = getPayUserlogByOrdersItem(paylist,ordersItem);
   					criteria.andIdIn(ids);
   				}
   			}
   			
   		}
   		
   		return example;
   	}
	/**
	 * 根据订单项条件获取相关订单号数据
	 * @param payList
	 * @param ordersItem
	 * @return
	 */
	public List<String> getPayUserlogByOrdersItem(List<PayUserlog> payList,OrdersItem ordersItem){
		List<String> ids = new ArrayList<String>();
		if(ordersItem != null){
			for(PayUserlog payUserlog:payList){
				String orderNo = payUserlog.getOrderNo();
				String skuId = payUserlog.getSkuId();
				String id = payUserlog.getId();
				ordersItem.setOrderNo(orderNo);
				ordersItem.setSkuId(skuId);
				OrdersItem item = null;
				item = ordersItemService.ordersItem(ordersItem);
				if(item != null){
					ids.add(id);
				}
			}
			
		}
		return ids;
	}
	
    public List<PayUserlog> findPayUserLogBycondition(PayUserlogExample example,String userId,PreType type,String orderNo,String startTime,String endTime) {
    	
    	List<PreIncomeVo> itemlist = new ArrayList<PreIncomeVo>();
		com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example
				.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andUserIdEqualTo(userId);
		criteria.andPreTypeEqualTo(type.getType());
		//条件查询
		if (StringHelper.isNotEmpty(orderNo)) {
			criteria.andOrderNoEqualTo(orderNo);
		}
		
		if(StringUtils.isNoneBlank(startTime,endTime)) {
			Date startDate = DateHelper.parseDate(startTime);
			Date endDate = DateHelper.parseDate(endTime);
			criteria.andCreateTimeBetween(startDate,endDate);
		}else {
			if(StringHelper.isNotEmpty(startTime)) {
				Date startDate = DateHelper.parseDate(startTime);
				criteria.andCreateTimeGreaterThan(startDate);
			}
			if(StringHelper.isNotEmpty(endTime)) {
				Date endDate = DateHelper.parseDate(endTime);
				criteria.andCreateTimeLessThan(endDate);
			}
		}
		example.setOrderByClause(" CREATE_TIME desc");
		List<PayUserlog> list = this.list(example);
    	return list;
    }
    /**
	 * 店铺订单用户支付记录ids
	 * 
	 * @param userId
	 * @return
	 */
    public List<String> getPayUserlogIds(String userId){
    	List<String> ids = this.payUserlogDao.getPayUserlogIds(userId);
    	return ids;
    }
    /***
     * 查找对应的支付记录
     * @param payUserlog
     * @return
     */
    public PayUserlog getPayType(PayUserlog payUserlog){
    	PayUserlog log = null;
    	if(payUserlog != null){
    		PayUserlogExample example = new PayUserlogExample();
			Criteria criteria = example.createCriteria();
			criteria.andOrderNoEqualTo(payUserlog.getOrderNo());
			criteria.andPayTypeIsNotNull();
			List<PayUserlog> logs= this.payUserlogDao.selectByExample(example);
			if(logs.size()>0){
				log = logs.get(0);
			}
    	}
    	return log;
    }
    
    public PayUserlog getPayUserlog(String orderNo,String skuId,String preIncomeType){
		PayUserlog payUserlog = null;
		if(StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(skuId) && StringHelper.isNotBlank(preIncomeType)){
			PayUserlogExample payUserlogExample = new PayUserlogExample();
			Criteria criteria = payUserlogExample.createCriteria();
			criteria.andOrderNoEqualTo(orderNo);
			criteria.andSkuIdEqualTo(skuId);
			criteria.andPreIncomeTypeEqualTo(preIncomeType);
			List<PayUserlog> list = this.payUserlogDao.selectByExample(payUserlogExample);
			if(list.size()>0){
				payUserlog = list.get(0);
			}
		}
		return payUserlog;
	}
    /**
	 * 根据用户id获取累计预估或者实际收益
	 * 
	 * @param userId
	 * @param preTytpe
	 * @return
	 */
	public int getPreOrActualNum(String userId, String preTytpe) {
		int totalNum = 0;
		List<PreIncomeVo> itemlist = new ArrayList<PreIncomeVo>();
		try {
			if (StringHelper.isNotBlank(userId)) {
				// 获取支付日志信息
				PayUserlogExample example = new PayUserlogExample();
				com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example
						.createCriteria();
				criteria.andIsEffectiveEqualTo(DBConst.TRUE);
				criteria.andUserIdEqualTo(userId);
				criteria.andPreTypeEqualTo(preTytpe);// 预估标识（001：预估，002：实际）
				List<PayUserlog> list = this.list(example);
				if(list.size()>0){
					totalNum = list.size();
				}
			}
		} catch (Exception e) {
		}
		return totalNum;
	}
	/**
	 * 查看用户最后一次提现
	 * */
	public List<PayUserlog> getWithDrawals(String userId) {
		PayUserlogExample example = new PayUserlogExample();
		com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example.createCriteria();
   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   		criteria.andTypeEqualTo(FinanceType.Reflect.getType());
   		example.setOrderByClause("create_time desc");
   		Page page = new Page();
   		page.setPageSize(1);
   		page.setRecordNow(0);
   		example.setPage(page);
   		List<PayUserlog> list = this.list(example);
		return list;
	}
	
	public  PayUserlog getTheLastPayUserLog(String userId) {
		PayUserlogExample example = new PayUserlogExample();
		com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example.createCriteria();
   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   		//criteria.andTypeEqualTo(FinanceType.Reflect.getType());
   		criteria.andUserIdEqualTo(userId);
   		example.setOrderByClause("create_time desc");
   		Page page = new Page();
   		page.setPageSize(1);
   		page.setRecordNow(0);
   		example.setPage(page);
   		List<PayUserlog> list = this.list(example);
   		if(list.isEmpty())
   			return null;
   		else
   			return list.get(0);
	}
	
	/**
	 * 获取提现总额
	 * @param userId
	 * @return
	 */
	public double getTotalAmount(String userId) {
		PayUserlogExample example = new PayUserlogExample();
		com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example.createCriteria();
   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   		criteria.andTypeEqualTo(FinanceType.Reflect.getType());
   		criteria.andUserIdEqualTo(userId);
   		example.setOrderByClause("create_time desc");
   		Page page = new Page();
   		page.setPageSize(1);
   		page.setRecordNow(0);
   		example.setPage(page);
   		List<PayUserlog> list = this.list(example);
   		double totalAmount =0;
   		if(!list.isEmpty())
   			totalAmount = list.get(0).getWithdrawTotalAmount()==null?0:list.get(0).getWithdrawTotalAmount();
   		return totalAmount;
	}
	
	public PayUserlog addWithDrawals(double totalWithDrawals,double balance,double amount,double fee,String userId) {
		
		PayUserlog payUserlog = new PayUserlog();
		//计算余额
		payUserlog.setBalance(balance-amount);
		payUserlog.setAmount(amount-fee);
		payUserlog.setUserId(userId);
		//提现手续费
		payUserlog.setWithdrawFee(fee);
		//退款
		payUserlog.setType(FinanceType.Reflect.getType());
		payUserlog.setExpendType("W001");
		payUserlog.setWithdrawState(WithDrawalsType.apply.getType());
		//计算总提现金额
		payUserlog.setWithdrawTotalAmount(totalWithDrawals+amount);
		//提现提示语
		this.add(payUserlog);
		return payUserlog;
	}
	
	private UsersMall addPreProfit(String result,String userId,Double commission,TaxCompany taxCompany,String orderNo,PreType preType,PreIncomeType preIncomeType,PreIncomeChannel channel,String skuId,TeamLevel teamLevel,UserType userType,OperateType operateType,Integer count) {
		if(commission!=null && userId!=null && StringUtils.isNotEmpty(userId)) {
			UsersMall parent= this.usersMallService.get(userId);
			//TODO 判断usersMall的角色
			if(parent !=null) {
				 this.addUserPreProfit(parent, commission.toString(), taxCompany, orderNo, preType, preIncomeType, channel, skuId, teamLevel, userType,operateType,false,count);
			}
			return parent;
		}
		return null;
	}
	/***
	 * 
	 * @param usersMall 用户
	 * @param commission 佣金
	 * @param taxCompany 公司的扣税
	 * @param orderNo 订单号
	 * @param preType 收益类型 
	 * @param channel 渠道
	 * @param skuId 商品规格Id
	 * @param operateType 预计操作
	 * @return
	 */
	public String addUserTeamPreProfit(UsersMall usersMall,String commission,TaxCompany taxCompany,String orderNo,PreType preType,PreIncomeChannel channel,String skuId,OperateType operateType,PreIncomeType preIncomeType,Integer count) {
		PreIncomeType incomeType = preIncomeType;
		PreIncomeType parentType = null;
		String result = SUCCESS;
		switch (preIncomeType) {
		case Commission:
			parentType = PreIncomeType.Bonus;
			break;
		case changeActual:
			parentType = PreIncomeType.changeActual;
			break;
		case tradeColse:
			parentType = PreIncomeType.tradeColse;
		default:
			break;
		}
		Double amount = this.addUserPreProfit(usersMall, commission, taxCompany, orderNo, preType, incomeType, channel, skuId, TeamLevel.My, UserType.ydz,operateType,true,count);
		usersMall = this.addPreProfit("", usersMall.getParentId(), amount, taxCompany, orderNo, preType, parentType, channel, skuId, TeamLevel.One, UserType.ydz,operateType,count);
		if(usersMall !=null)
			this.addPreProfit("", usersMall.getParentId(), amount, taxCompany, orderNo, preType,parentType, channel, skuId, TeamLevel.Two, UserType.ydz,operateType,count);
		return result;
	}
	
	public Double addUserPreProfit(UsersMall usersMall,String commission,TaxCompany taxCompany,String orderNo,PreType preType,PreIncomeType preIncomeType,PreIncomeChannel channel,String skuId,TeamLevel teamLevel,UserType userType,OperateType operateType,boolean isTaxPercent,Integer count) {
		Double amount = this.savePreAmountByTax(usersMall, commission, taxCompany, orderNo, preType, preIncomeType, channel, skuId,teamLevel,userType,operateType,isTaxPercent,count);
		if(amount !=null) {
			String result = SUCCESS;
			AlertType alertType =null;
			switch (preType) {
			case pre:
				double oldProfit = usersMall.getPreProfit() ==null?0:usersMall.getPreProfit();
				if(OperateType.add.equals(operateType))
					oldProfit =oldProfit +amount*count;
				else
					oldProfit =oldProfit -amount*count;
				oldProfit = oldProfit<=0?0:oldProfit;
				usersMall.setPreProfit(oldProfit);
				alertType = AlertType.pre;
				break;
			case actual:
				double money = usersMall.getMoney() ==null?0:usersMall.getMoney();
				money =money +amount*count;
				usersMall.setMoney(money);
				double actualPre = usersMall.getTotalProfit()==null?0:usersMall.getTotalProfit();
				actualPre = actualPre+amount*count;
				usersMall.setTotalProfit(actualPre);
				alertType = AlertType.actual;
				break;
			}
			result = this.usersMallService.edit(usersMall);
			double totalAmount = amount*count;
			this.appPushService.pushMsg(usersMall,alertType, null,new MsgVO(totalAmount));
		}
		return amount;
	}
	
	public Double savePreAmountByTax(UsersMall usersMall,String commission,TaxCompany taxCompany,String orderNo,PreType preType,PreIncomeType preIncomeType,PreIncomeChannel channel,String skuId,TeamLevel level,UserType userType,OperateType operateType,boolean isTaxPercent,Integer count) {
		//计算各渠道获取的佣金
		Double amount = this.calPreAmountByTax(usersMall, commission, taxCompany, level, userType, isTaxPercent, count);
	/*	Double amount  = Double.parseDouble(commission);
		//TODO 查看佣金百分比
		ProjectCommission projectCommission = this.projectCommissionService.getCommissionByLevelAndUserTypeAndTeamCount(level.getLevel(),userType.getType(), 100,taxCompany.getValue());
		if(!TaxCompany.yh.getValue().equals(taxCompany.getValue()) && isTaxPercent) {
			String totalCommission = TaxCompany.calCommission(commission, taxCompany);
			amount = Double.parseDouble(totalCommission);
		}
		String userCommission = this.projectCommissionService.getUserCommission(projectCommission, amount);
		amount = StringUtils.isNotEmpty(userCommission)?Double.parseDouble(userCommission):0;
		*/
		count= count==null?1:count;
		double totalAmount = amount * count;
		String result = this.addProfitAmount(usersMall.getId(), orderNo, preType, totalAmount, preIncomeType, channel, skuId,operateType);
		if(!SUCCESS.equals(result))
			amount =null;
		return amount; 
	}
	
	public Double calPreAmountByTax(UsersMall usersMall,String commission,TaxCompany taxCompany ,TeamLevel level,UserType userType,boolean isTaxPercent,Integer count) {
		//计算各渠道获取的佣金
		Double amount  = Double.parseDouble(commission);
		//查看佣金百分比
		ProjectCommission projectCommission = this.projectCommissionService.getCommissionByLevelAndUserTypeAndTeamCount(level.getLevel(),userType.getType(), 100,taxCompany.getValue());
		if(!TaxCompany.yh.getValue().equals(taxCompany.getValue()) && isTaxPercent) {
			String totalCommission = TaxCompany.calCommission(commission, taxCompany);
			amount = Double.parseDouble(totalCommission);
		}
		String userCommission = this.projectCommissionService.getUserCommission(projectCommission, amount);
		amount = StringUtils.isNotEmpty(userCommission)?Double.parseDouble(userCommission):0;
		return amount; 
	}
	
	public String addProfitAmount(String userId,String orderNo,PreType preType,double amount,PreIncomeType preIncomeType,PreIncomeChannel preIncomeChannel,String skuId,OperateType operateType) {
		PayUserlog payUserlog = new PayUserlog();
		payUserlog.setPreType(preType.getType());
		payUserlog.setPreAmount(amount);
		payUserlog.setPreIncomeChannel(preIncomeChannel.getState());
		payUserlog.setPreIncomeType(preIncomeType.getType());
		payUserlog.setSkuId(skuId);
		payUserlog.setUserId(userId);
		payUserlog.setOrderNo(orderNo);
		payUserlog.setPreOperateType(operateType.toString());
		String result = this.add(payUserlog);
		return result;
	}
	
	public String addPayAmount(String userId,FinanceType financeType,Double amount,PayType payType, String orderNo,String payNo,Date payTime) {
		PayUserlog payLog = new PayUserlog();
		payLog.setAmount(amount);
		payLog.setOrderNo(orderNo);
		payLog.setPayNo(payNo);
		payLog.setUserId(userId);
		payLog.setType(financeType.getType());//账务类型（001：收入，002：支出,003:提现）
		payLog.setPayType(payType.getType());//支付类型（001：支付宝，002：微信，003：余额）
		payLog.setPayTime(payTime);
		String result = this.add(payLog);
		return result;
	}
	
	public List<PayUserlog> getPreAmountByOrderNoAndSkuIdAndType(String orderNo,String skuId,PreType preType) {
		PayUserlogExample example = new PayUserlogExample();
		com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlogExample.Criteria criteria = example.createCriteria();
   		criteria.andOrderNoEqualTo(orderNo);
   		criteria.andSkuIdEqualTo(skuId);
   		criteria.andPreTypeEqualTo(preType.getType());
   		List<PayUserlog> payUserlogs = this.list(example);
   		return payUserlogs;
	}
	
	/*public double calRemainCommission(String commission,String orderNo,String skuId) {
		List<PayUserlog> payUserlogs = this.getPreAmountByOrderNoAndSkuIdAndType(orderNo, skuId, PreType.actual);
		Double payCommission = 0d;
		for(PayUserlog payUserlog : payUserlogs)
			payCommission +=payUserlog.getAmount();
		String remainCommission = NumberStringHelper.subtractString(commission, Double.toString(payCommission));
		Double rc = Double.parseDouble(remainCommission);
		return rc<=0?0:rc;
	}*/
	
	public double calRemainCommission(UsersMall yunUser,String commission,TaxCompany taxCompany,int count) {
		String remainCommission = "0";
		if(yunUser==null) 
			remainCommission = commission;
		else {
			switch (taxCompany) {
				case yh:
					remainCommission = commission;
					break;
				case jd:
					Double amount = this.calPreAmountByTax(yunUser, commission, taxCompany, TeamLevel.My, UserType.ydz, true, count);
					if(yunUser.getParentId()!=null) {
						UsersMall oneYunUser = this.usersMallService.get(yunUser.getParentId());
						if(oneYunUser!=null) {
							amount+=this.calPreAmountByTax(oneYunUser, commission, taxCompany, TeamLevel.One, UserType.ydz, false, count);
							if(oneYunUser.getParentId()!=null) {
								UsersMall twoYunUser = this.usersMallService.get(oneYunUser.getParentId());
								amount+=this.calPreAmountByTax(twoYunUser, commission, taxCompany, TeamLevel.Two, UserType.ydz, false, count);
							}
						}
					}
					remainCommission= NumberStringHelper.subtractString(commission, Double.toString(amount));
					break;
			}
		}
		remainCommission = NumberStringHelper.mulString(remainCommission, Double.toString(count));
		return Double.parseDouble(remainCommission);
	}
	
	
}